﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BoYuanCore.CodeGenerator.code;
using FineUIPro;
using FreeSql.Aop;
using FreeSql.Internal;

namespace BoYuanCore.CodeGenerator.Public
{
    public partial class DBMigration : FineUIPage
    {
        private static IFreeSql DB = null;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ShowConnectionString();
            }
        }

        protected void btn_test_OnClick(object sender, EventArgs e)
        {
            //
            InitFreeSqlInstance();
            try
            {
                if (DB.Ado.ExecuteConnectTest())
                {
                    NotifySuccess("测试连接成功");
                }
                else
                {
                    NotifyQuestion("测试连接失败,请检查连接字符串");
                }
            }
            catch (Exception exception)
            {
                AlertError("连接异常:" + exception.Message);
            }
        }

        protected void btn_DbInit_OnClick(object sender, EventArgs e)
        {
            InitFreeSqlInstance();

            //创建表 FreeSqlBuilder.UseAutoSyncStructure(true) 执行curd会自动同步表结构 
            DB.Select<DBD.Entity.SysAdmin>().Any();
            DB.Select<DBD.Entity.SysModulePermissions>().Any();
            DB.Select<DBD.Entity.SysLoginLog>().Any();
            DB.Select<DBD.Entity.SysModule>().Any();
            DB.Select<DBD.Entity.SysRole>().Any();

            //添加初始数据
            //SysAdmin
            DBD.Entity.SysAdmin admin = new DBD.Entity.SysAdmin
            {
                ID = 1,
                LoginName = "admin",
                RealName = "超级管理员",
                Password = "ddc102d75efefa2370616ad931572661",//123456
                RoleID = 1,
                Remark = "超级管理员不可删除",
                Photo = "/res/images/head/boy/1.jpg",
                Sort = 1000,
                IsDel = false
            };
            DB.Insert(admin).ExecuteAffrows();

            //SysModulePermissions
            List<DBD.Entity.SysModulePermissions> sysModulePermissionsList = new List<DBD.Entity.SysModulePermissions>()
            {
                new DBD.Entity.SysModulePermissions(){ID =1,RoleID= 1,PageID=1},
                new DBD.Entity.SysModulePermissions(){ID =2,RoleID= 1,PageID=2},
                new DBD.Entity.SysModulePermissions(){ID =3,RoleID= 1,PageID=3},
                new DBD.Entity.SysModulePermissions(){ID =4,RoleID= 1,PageID=4},
                new DBD.Entity.SysModulePermissions(){ID =5,RoleID= 1,PageID=5},
                new DBD.Entity.SysModulePermissions(){ID =6,RoleID= 1,PageID=6},
                new DBD.Entity.SysModulePermissions(){ID =7,RoleID= 1,PageID=7},
                new DBD.Entity.SysModulePermissions(){ID =8,RoleID= 1,PageID=8},
                new DBD.Entity.SysModulePermissions(){ID =9,RoleID= 1,PageID=9},
                new DBD.Entity.SysModulePermissions(){ID =10,RoleID=1,PageID=10},
                new DBD.Entity.SysModulePermissions(){ID =11,RoleID=1,PageID=11},
                new DBD.Entity.SysModulePermissions(){ID =12,RoleID=1,PageID=12},
                new DBD.Entity.SysModulePermissions(){ID =13,RoleID=1,PageID=13},
            };
            DB.Insert(sysModulePermissionsList).ExecuteAffrows();

            //SysLoginLog 不需要添加基础数据

            //SysModule
            List<DBD.Entity.SysModule> moduleList = new List<DBD.Entity.SysModule>()
            {
new DBD.Entity.SysModule(){ID=1,	ParentID=0,	IsLeaf=false,	TreePath="1,",	IsHidden=false,	PageTitle="网站管理员",	Url="",	Icon="res/icon/tux.png",	FontIcon="",	Sort=1000,	Remark="",	ButtonID="",	ButtonText="",},
new DBD.Entity.SysModule(){ID=2,	ParentID=1,	IsLeaf=false,	TreePath="1,2,",	IsHidden=false,	PageTitle="页面组件",	Url="/admin/sysmodule/index",	Icon="res/icon/page_code.png",	FontIcon="",	Sort=1000,	Remark="",	ButtonID="",	ButtonText="",},
new DBD.Entity.SysModule(){ID=3,	ParentID=2,	IsLeaf=true,	TreePath="1,2,3,",	IsHidden=true,	PageTitle="添加页面",	Url="/admin/sysmodule/add",	Icon="",	FontIcon="StarO",	Sort=1000,	Remark="",	ButtonID="",	ButtonText="",},
new DBD.Entity.SysModule(){ID=4,	ParentID=2,	IsLeaf=true,	TreePath="1,2,4,",	IsHidden=true,	PageTitle="设置图标",	Url="/admin/sysmodule/icons",	Icon="",	FontIcon="",	Sort=1000,	Remark="",	ButtonID="",	ButtonText="",},
new DBD.Entity.SysModule(){ID=5,	ParentID=1,	IsLeaf=false,	TreePath="1,5,",	IsHidden=false,	PageTitle="后台角色",	Url="/admin/sysrole/index",	Icon="res/icon/award_star_bronze_2.png",	FontIcon="",	Sort=1000,	Remark="",	ButtonID="",	ButtonText="",},
new DBD.Entity.SysModule(){ID=6,	ParentID=5,	IsLeaf=true,	TreePath="1,5,6,",	IsHidden=true,	PageTitle="设置角色",	Url="/admin/sysrole/add",	Icon="",	FontIcon="",	Sort=1000,	Remark="",	ButtonID="",	ButtonText="",},
new DBD.Entity.SysModule(){ID=7,	ParentID=1,	IsLeaf=true,	TreePath="1,7,",	IsHidden=false,	PageTitle="用户管理",	Url="/admin/sysadmin/index",	Icon="res/icon/group_add.png",	FontIcon="",	Sort=1000,	Remark="",	ButtonID="",	ButtonText="",},
new DBD.Entity.SysModule(){ID=8,	ParentID=1,	IsLeaf=false,	TreePath="1,8,",	IsHidden=false,	PageTitle="登录日志",	Url="/admin/sysloginlog/index",	Icon="res/icon/book_red.png",	FontIcon="",	Sort=1000,	Remark="",	ButtonID="",	ButtonText="",},
new DBD.Entity.SysModule(){ID=9,	ParentID=7,	IsLeaf=true,	TreePath="1,7,9,",	IsHidden=true,	PageTitle="添加用户",	Url="/admin/sysadmin/add",	Icon="res/icon/bullet_disk.png",	FontIcon="",	Sort=1000,	Remark="",	ButtonID="",	ButtonText="",},
new DBD.Entity.SysModule(){ID=10,	ParentID=7,	IsLeaf=true,	TreePath="1,7,10,",	IsHidden=true,	PageTitle="查看用户",	Url="",	Icon="",	FontIcon="",	Sort=1000,	Remark="",	ButtonID="",	ButtonText="",},
new DBD.Entity.SysModule(){ID=11,	ParentID=2,	IsLeaf=true,	TreePath="1,2,11,",	IsHidden=true,	PageTitle="图标设置",	Url="/admin/sysmodule/icons",	Icon="",	FontIcon="",	Sort=1000,	Remark="",	ButtonID="",	ButtonText="",},
new DBD.Entity.SysModule(){ID=12,	ParentID=2,	IsLeaf=true,	TreePath="1,2,12,",	IsHidden=true,	PageTitle="字体图标1",	Url="/admin/sysmodule/iconfonts",	Icon="",	FontIcon="",	Sort=1000,	Remark="",	ButtonID="",	ButtonText="",},
new DBD.Entity.SysModule(){ID=13,  ParentID = 2, IsLeaf = true, TreePath="1,2,13,", IsHidden =true, PageTitle ="字体图标2", Url="/admin/sysmodule/iconfontsfa", Icon = "", FontIcon = "", Sort = 1000, Remark = "", ButtonID = "", ButtonText = "", },
            };

            DB.Insert(moduleList).ExecuteAffrows();

            //SysRole
            DBD.Entity.SysRole role=new DBD.Entity.SysRole()
            {
                ID = 1,
                RoleName = "超级管理员",
                IsDel = false,
                Remark = "超级管理员角色不能删除"
            };

            DB.Insert(role).ExecuteAffrows();

            AlertSuccess("初始化数据库和基础数据成功！");
        }

        public void InitFreeSqlInstance()
        {
            switch (ddl_db.SelectedText)
            {
                case "SqlServer":
                    DB = new FreeSql.FreeSqlBuilder()
                        .UseConnectionString(FreeSql.DataType.SqlServer, txb_url.Text)
                        .UseAutoSyncStructure(true) //自动同步实体结构到数据库
                        //.UseMonitorCommand(cmd => Logger.Default.Debug(cmd.CommandText))
                        .UseNoneCommandParameter(true)
                        .Build(); //请务必定义成 Singleton 单例模式
                    break;

                case "MySql":
                    DB = new FreeSql.FreeSqlBuilder()
                        .UseConnectionString(FreeSql.DataType.MySql, txb_url.Text)
                        .UseAutoSyncStructure(true) //自动同步实体结构到数据库
                        //.UseMonitorCommand(cmd => Logger.Default.Debug(cmd.CommandText))
                        .UseNoneCommandParameter(true)
                        .Build(); //请务必定义成 Singleton 单例模式
                    break;

                case "Oracle":
                    DB = new FreeSql.FreeSqlBuilder()
                        .UseConnectionString(FreeSql.DataType.Oracle, txb_url.Text)
                        .UseAutoSyncStructure(true) //自动同步实体结构到数据库
                        //.UseMonitorCommand(cmd => Logger.Default.Debug(cmd.CommandText))
                        .UseNoneCommandParameter(true)
                        .UseNameConvert(NameConvertType.ToUpper)//表名称全局大写
                        .Build(); //请务必定义成 Singleton 单例模式
                    break;

                case "PostgreSQL":
                    DB = new FreeSql.FreeSqlBuilder()
                        .UseConnectionString(FreeSql.DataType.PostgreSQL, txb_url.Text)
                        .UseAutoSyncStructure(true) //自动同步实体结构到数据库
                        //.UseMonitorCommand(cmd => Logger.Default.Debug(cmd.CommandText))
                        .UseNoneCommandParameter(true)
                        .UseNameConvert(NameConvertType.ToLower)//表名称全局小写
                        .Build(); //请务必定义成 Singleton 单例模式
                    break;
            }

            EventHandler<ConfigEntityPropertyEventArgs> tempEventHandler = (s, ce) =>
            {
                //默认情况 c# 枚举会映射为 MySql Enum 类型，如果想映射为 int 在 FreeSqlBuilder Build 之后执行以下 Aop 统一处理。https://github.com/dotnetcore/FreeSql/wiki/%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98
                //if (DB.Ado.DataType == DataType.MySql && ce.Property.PropertyType.IsEnum)

                //为了LookSQL能正常显示Enum特性的值
                if (ce.Property.PropertyType.IsEnum)
                    ce.ModifyResult.MapType = typeof(int);
            };
            DB.Aop.ConfigEntityProperty -= tempEventHandler;//防止重复添加事件
            DB.Aop.ConfigEntityProperty += tempEventHandler;

        }

        protected void ddl_db_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            ShowConnectionString();
        }

        private void ShowConnectionString()
        {
            switch (ddl_db.SelectedText)
            {
                case "SqlServer":
                    txb_showStr.Text = "server=.;database=BoYuan4;uid=sa;pwd=123456";
                    break;

                case "MySql":
                    txb_showStr.Text = "Data Source=127.0.0.1;Port=3306;User ID=root;Password=123456; Initial Catalog=boyuan4;Charset=utf8; SslMode=none;Min pool size=1";
                    break;

                case "Oracle":
                    //系统dba
                    //User Id=SYS;Password=123456;Data Source=//127.0.0.1:1521/ORCL;Pooling=true;Min Pool Size=1;DBA Privilege=SYSDBA;
                    txb_showStr.Text = "User Id=SYS;Password=123456;Data Source=//127.0.0.1:1521/ORCL;Pooling=true;Min Pool Size=1;";
                    break;

                case "PostgreSQL":
                    txb_showStr.Text = "Host=127.0.0.1;Port=5432;Username=postgres;Password=123456;Database=BoYuan4;Pooling=true;Minimum Pool Size=1";
                    break;

                default:
                    txb_showStr.Text = "无";
                    break;
            }

        }


    }
}